<!-- Login.vue -->
<template>
  <div>
    <h2>Login_SESSION</h2>
    <form @submit.prevent="handleLogin">
      <div>
        <label for="username">Username:</label>
        <input type="text" v-model="username" id="username" required />
      </div>
      <div>
        <label for="password">Password:</label>
        <input type="password" v-model="password" id="password" required />
      </div>
      <button type="submit">Login</button>
    </form>
    <p v-if="error">{{ error }}</p>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'

const router = useRouter()
const username = ref('')
const password = ref('')
const error = ref('')

const handleLogin = async () => {
  try {
    const response = await axios.post(
      'http://localhost:3000/login',
      {
        username: username.value,
        password: password.value,
      },
      {
        withCredentials: true, // 允许发送 cookies
      }
    )

    if (response.data.success) {
      alert('Logged in successfully')
      // 重定向到用户个人资料页面
      console.log('验证成功后，查看response', response)
      let username = response.data.user.username
      router.push(`/profile?user=${username}`)
    } else {
      error.value = 'Invalid credentials'
    }
  } catch (err) {
    err.value = 'An error occurred'
  }
}
</script>
